package com.itmuch.providerdemo.ribbon;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import com.netflix.niws.loadbalancer.DiscoveryEnabledServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

public class MyMetadataBasedRule extends AbstractLoadBalancerRule {
    @Autowired
    private EurekaInstanceConfigBean eurekaInstanceConfigBean;

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {
        // 读取ribbon配置
    }

    @Override
    public Server choose(Object key) {
        // 1. 读取自身配置文件里面的元数据
        Map<String, String> metadataMap = eurekaInstanceConfigBean.getMetadataMap();
        String version = metadataMap.get("version");

        // 2. 读取provider微服务的元数据
        ILoadBalancer loadBalancer = this.getLoadBalancer();
        List<Server> reachableServers = loadBalancer.getReachableServers();

        // 3. 筛选出元数据匹配的provider实例列表
        List<Server> metadataMatchedServers = reachableServers.stream()
                .filter(server -> {
                    DiscoveryEnabledServer des = (DiscoveryEnabledServer) server;
                    Map<String, String> metadata = des.getInstanceInfo().getMetadata();
                    String version1 = metadata.get("version");
                    return Objects.equals(version1, version);
                })
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(metadataMatchedServers)) {
            return null;
        }

        int i = ThreadLocalRandom.current().nextInt(metadataMatchedServers.size());

        // 4. 负载均衡算法，选择1个返回
        return metadataMatchedServers.get(i);
    }
}
